import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
import { DefaultStage } from '../default-stage';
import { Helper } from 'babylon-lib/tool/helper';
import { RawAssetsName, RawAssetsUrl } from '../../raw-assets-info';
import { ParticleSystem } from '@babylonjs/core/Particles/particleSystem';
import { Color3, Color4 } from '@babylonjs/core/Maths/math.color';
import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder';
import { Vector3 } from '@babylonjs/core/Maths/math.vector';
import { RenderOrder } from 'babylon-lib/misc/render-order';
import * as Data from '../../data/data';
import { Landscape } from './landscape';


class Wreckage {

    private static _models: TransformNode[] = [];
    private static _pss: ParticleSystem[] = [];

    public static initialize(stage: DefaultStage): void {
        Helper.nodeInArray(RawAssetsName.wreckage, stage.mainScene.meshes, this._models, false);

        for (const md of this._models) {
            const ps = this.generatePS(stage, md);
            this._pss.push(ps);
        }
    }

    private static generatePS(stage: DefaultStage, model: TransformNode): ParticleSystem {
        const duration = 20;
        const count = 50;
        const power = 0.1;
        const color = Color3.FromHexString('#cecece');
        const size = 2;
        const scn = stage.mainScene;
        const texture = stage.loader(scn).getTextureTaskInfo(RawAssetsUrl.textureYanwu)?.texture!;

        const ps = new ParticleSystem(model.name + '-particle-system', count, scn);
        ps.particleTexture = texture;

        const m = MeshBuilder.CreateBox(model.name + '-particales-emmiter', { size: 1 }, scn);
        m.visibility = 0;
        ps.emitter = m;
        ps.minInitialRotation = 0;
        ps.maxInitialRotation = 6.28;
        ps.minLifeTime = duration * 0.5;
        ps.maxLifeTime = duration;
        ps.minAngularSpeed = -0.2;
        ps.maxAngularSpeed = 0.2;

        ps.emitRate = count * 0.25;
        ps.createSphereEmitter(1, 1);
        ps.minEmitPower = power;
        ps.maxEmitPower = power * 2;
        ps.updateSpeed = 0.02;
        const grv = new Vector3().copyFrom(Landscape.wind);
        grv.y = 0.4;
        ps.gravity = grv;

        ps.addColorGradient(0, new Color4(color.r, color.g, color.b, 0));
        ps.addColorGradient(0.02, new Color4(color.r, color.g, color.b, 0.6));
        ps.addColorGradient(1, new Color4(color.r, color.g, color.b, 0));

        ps.addSizeGradient(0, size * 0.5, size);
        ps.addSizeGradient(0.3, size, size * 2);
        ps.addSizeGradient(1, size * 5, size * 10);

        ps.addVelocityGradient(0, 0, 1);

        ps.emitter.parent = model;
        ps.emitter.position.set(0, 0, 0);
        ps.blendMode = ParticleSystem.BLENDMODE_STANDARD;
        ps.renderingGroupId = RenderOrder.id(Data.orders.scene);
        ps.preWarmCycles = 500;
        ps.start();
        return ps;
    }

}


export { Wreckage };